import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import {
  removeSelectedComponent,
  //   changeComponentHidden,
  //   toggleComponentLocked,
  selectPrevComponent,
  selectNextComponent,
  copiedComponent,
  pasteComponent,
} from "@/store/componentReducer";
import { ActionCreators } from "redux-undo";

function isActiveElementEditable() {
  const activeElement = document.activeElement;

  if (activeElement == document.body) return true;

  //添加dnd后会选中他自己的元素 挑选选中的元素
  if (activeElement?.matches("div[role='button']")) return true;

  return false;
}
const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch();
  //删除
  useKeyPress(["delete", "backspace"], () => {
    if (!isActiveElementEditable()) return;

    dispatch(removeSelectedComponent());
  });
  //复制
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementEditable()) return;
    dispatch(copiedComponent());
  });
  //粘贴
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementEditable()) return;
    dispatch(pasteComponent());
  });
  //上移动
  useKeyPress(["uparrow"], () => {
    if (!isActiveElementEditable()) return;
    dispatch(selectPrevComponent());
  });
  //下移动
  useKeyPress(["downarrow"], () => {
    if (!isActiveElementEditable()) return;
    dispatch(selectNextComponent());
  });
  //撤销
  useKeyPress(["ctrl.z", "meta.z"], () => {
    dispatch(ActionCreators.undo());
  });
  //重做
  useKeyPress(["ctrl.y", "meta.y"], (e: KeyboardEvent) => {
    e.preventDefault();
    dispatch(ActionCreators.redo());
  });
};

export default useBindCanvasKeyPress;
